const router = require("koa-router")()
router.prefix("/admin")

const { User, DangAn, AddressList } = require("../models/users")

const {CtxBody, APPID, SECRET_KEY, ServerUrl} = require("../models/config")

const axios = require("axios")

const { writeImage } = require("../models/multer")

const fs = require("fs")

const request = require("request")

// 获取会员数据

router.post("/getMemberData", async ctx => {
    let  id  = ctx.state.user.id 
    if (id) {
        let user = await User.findOne({ _id: id })
        if (user) {
            CtxBody(ctx, 200, user)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 保存用户手机号码

router.post("/savePhone", async ctx => {
    let { phone } = ctx.request.body 
    let id = ctx.state.user.id 
    if (phone && id) {
        let res = await User.findOneAndUpdate({ _id: id }, {
            $set: {
                phone
            }
        }, { new: true })
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 会员添加档案

router.post("/addUserDangan", async ctx => {
    let id = ctx.state.user.id 
    let { danganid, relationship,hasChildren, gender, name, birthday, top, weight, yaowei, issmoke, isdriking, liver, kidney, marry, guomin, foodguomin, family, man, selfdone } = ctx.request.body  
    if (danganid) {

        let res = await DangAn.findOneAndUpdate({ _id: dananid }, {
            $set: {
                relationship,
                gender, 
                name,
                birthday,
                top,
                weight,
                yaowei,
                issmoke,
                isdriking,
                liver,
                kidney,
                marry,
                guomin,
                foodguomin,
                family,
                hasChildren,
                man,
                selfdone
            }
        }, { new: true })
        CtxBody(ctx, 204, "")
    } else {
        let newdanan = new DangAn({
                relationship,
                gender, 
                name,
                birthday,
                top,
                weight,
                yaowei,
                issmoke,
                isdriking,
                liver,
                kidney,
                marry,
                guomin,
                foodguomin,
                family,
                hasChildren,
                man,
                selfdone,
                beLong: id
        })
        let ret = await newdanan.save()
        if (ret) {
            let update = await User.findOneAndUpdate({_id: id}, {
                $push: {
                    mydangan: ret._id
                }
            })
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 404, "")
        }
    }
})

// 用户隐藏档案

router.post("/changeDanganStatus", async ctx => {
    let { id } = ctx.request.body
    if (id) {
        let res = await DangAn.findOne({ _id: id })
        if (res.status == 1) {
            let ret = await DangAn.findOneAndUpdate({ _id: id }, {
                $set: {
                    status: "2"
                }
            })
            CtxBody(ctx, 204, "")
        } else {
            let ret = await DangAn.findOneAndUpdate({ _id: id }, {
                $set: {
                    status: "1"
                }
            })
            CtxBody(ctx, 204, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 用户获取档案

router.post("/getUserDangan", async ctx => {
    let id = ctx.state.user.id 
    if (id) {
        let dangan = await User.findOne({ _id: id},"mydangan").populate({ path: "mydangan", match: {status: "1"}})
        CtxBody(ctx, 200, dangan)
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 根据ID查找档案

router.post("/getDanganByID", async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await DangAn.findOne({ _id: id })
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 用户加入分销
 
router.post("/joinfenxiao", async ctx => {
    let id = ctx.state.user.id 
    if (id) {
        let res = await User.findOneAndUpdate({ _id: id }, {
            $set: {
                distribution: "1"
            }
        }, { new: true })
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
}) 

// 用户生成 二维码

router.post("/createCode", async ctx => {
    let { path,width } = ctx.request.body 
    let id = ctx.state.user.id
    let name = `${new Date().getTime()}.jpg`
    let access_token = ""
    let URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET_KEY}`
    let res = await axios.get(URL)
    if (res.data.access_token) {
        access_token = res.data.access_token
        let codeUrl = `https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${access_token}`
        let header = {
            "content-type": "image/jpg"
        }
        let json = {
            path,
            width,
        }
        let data = await request.post({url:codeUrl, json}).pipe(fs.createWriteStream(`public/images/${name}`))
        let codename = `${ServerUrl}/public/images/${name}`
        let update = await User.findOneAndUpdate({ _id: id }, {
            $set: {
                qrcode: codename
            }
        })
        CtxBody(ctx, 200, codename )
        
        
    } else {
        CtxBody(ctx, 404, "")
    }
    
})

// 用户获取二维码

router.post("/getqrCode", async ctx => {
    let id = ctx.state.user.id
    if (id) {
        let res = await User.findOne({ _id: id }, "qrcode")
        if(res.qrcode) {
            CtxBody(ctx, 200, res.qrcode)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 用户添加地址

router.post("/addUserAddress", async ctx => {
    let { name, phone, address, left, top, province, city, country, defaultAdd, addid } = ctx.request.body 
    let userid = ctx.state.user.id 
    if (addid) {
        let res = await AddressList.findOneAndUpdate({ _id: addid }, {
            $set: {
                name,
                phone,
                address,
                left,
                top,
                province,
                city,
                country,
                defaultAdd,
               
            }
        }, { new: true })
        CtxBody(ctx, 204, "")
    } else {
        let newadd = new AddressList({
                name,
                phone,
                address,
                left,
                top,
                province,
                city,
                country,
                defaultAdd,
              
        })
        let ret = await newadd.save()
        let update = await User.findOneAndUpdate({ _id: userid }, {
            $push: {
                addressList: ret._id
            }
        }, { new: true })
        console.log(ret);
        
        if (ret.defaultAdd == 1) {
            let all = await AddressList.updateMany({ _id: { $ne: ret._id }}, { $set: { defaultAdd: "2"}})
            
        }
        console.log(3);
        
        CtxBody(ctx, 204, "")
    }
})

// 获取用户的地址列表

router.post("/getUserAddress", async ctx => {
    let id = ctx.state.user.id
    if (id) {
        let res = await User.findOne({ _id: id }, "addressList").populate({ path : "addressList", match: { status: "1" }, options: { sort: { defaultAdd: 1}} })
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 根据id获取地址

router.post("/getUserAddressByID", async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await AddressList.findOne({ _id: id }, "_id name phone address province city country defaultadd")
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 根据id隐藏地址

router.post("/changeStatusAddressByID", async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await AddressList.findOneAndUpdate({ _id: id }, {$set: { status: "2"}})
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 获取用户的默认地址

router.post("/getUserDefaultAddress", async ctx => {
    let id = ctx.state.user.id 
    let res = await User.findOne({ _id: id }, "addressList").populate({ path: "addressList",match:{defaultAdd: "1", status: "1"}})
    if (res) {
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 获取用户余额

router.post("/getUserMoney", async ctx => {
    let id = ctx.state.user.id 
    if (id) {
        let res = await User.findOne( { _id: id }, "money")
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 获取用户的下级会员

router.post("/getUserChildren", async ctx => {
    let id = ctx.state.user.id 
    if (id) {
        let res = await User.findOne({ _id: id }, "children").populate({
            path: "children",
            match: {
                status: "1"
            },
            select:"_id nickname avatar role phone"
        })
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 获取用户的上级

router.post("/getUserSub", async ctx => {
    let id = ctx.state.user.id 
    if (id) {
        let res = await User.findOne({ _id: id }, "sub").populate({
            path: "sub",
            match: {
                status: "1"
            },
            select:"_id nickname avatar role phone"

        }) 
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 30003, "")
    }
})



module.exports = router